import { Injectable, HttpService } from '@nestjs/common'
import { MailerService } from '@nestjs-modules/mailer'
import { EmailCodeDto } from './dto/email-code.dto'
import { SendEmailCode } from '../../template/sendEmailCode'
import { CacheService } from '../cache/cache.service'
import { PhoneCodeDto } from './dto/phone-code.dto'
import * as qs from 'qs'
import { map } from 'rxjs/operators'
import { TrafficDto } from './dto/trafficDto'

@Injectable()
export class EmailService {
  constructor(
    private readonly mailerService: MailerService,
    private readonly httpService: HttpService,
    private readonly cacheService: CacheService
  ) {}

  async sendEmailCode(emailCode: EmailCodeDto) {
    const { loginEmail } = emailCode
    const code = Math.floor(Math.random() * (999999 - 100000)) + 100000
    const html = new SendEmailCode(loginEmail, code)
    await this.cacheService.set(loginEmail, code, 60 * 5)

    await this.mailerService.sendMail({
      to: loginEmail,
      from: '1435877784@qq.com',
      subject: 'Blog 邮箱验证',
      html: html.html
      // template: 'emailValidation'
    })
  }

  async sendPhoneCode(phoneCode: PhoneCodeDto) {
    const { phone } = phoneCode
    const data = {
      phoneVal: phone,
      type: 21
    }
    return await this.httpService.post(
      'https://m.10010.com/god/AirCheckMessage/sendCaptcha',
      qs.stringify(data),
      {
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
        },
      },
    ).pipe(map(response => response.data)).toPromise()
    // const result = await this.httpService.get('https://api.github.com/users/januwA').toPromise()
  }

  async getTraffic(trafficCode: TrafficDto) {
    const { number, captcha } = trafficCode
    const params = {
      number,
      captcha,
      type: 21
    }

    // ?number=' + number + '&type=21' + '&captcha=' + captcha
    return await this.httpService.get(
      'https://m.10010.com/god/qingPiCard/flowExchange',
      { params }
    ).pipe(map(response => response.data)).toPromise()
  }
}
